package com.gomyb.admin.web.listener;

import com.gomyb.admin.module.user.model.SysPermission;
import com.gomyb.admin.module.user.service.SysPermissionService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author <a href="mailto:hellohesir@gmail.com">Mr_He</a>
 */
@Component
@Log4j2
public class SpringMvcUrlListener implements ServletContextListener {

    @Autowired
    private RequestMappingHandlerMapping handlerMapping;

    @Autowired
    private SysPermissionService sysPermissionService;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        Set<RequestMappingInfo> rmSet = handlerMapping.getHandlerMethods().keySet();
        List<SysPermission> sysPermissionList = new ArrayList<>();
        List<String> urls = new ArrayList<>(rmSet.size());
        for (RequestMappingInfo rm : rmSet) {
            SysPermission permission = new SysPermission();
            String url = rm.getPatternsCondition().getPatterns().iterator().next();
            if(!urls.contains(url)) {
                urls.add(url);
                permission.setPermissionUrl(url);
                permission.setPermissionName(rm.getName());
                sysPermissionList.add(permission);
            }
        }
        sysPermissionService.saveOrUpdate(sysPermissionList);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }
}
